package java67_adv7;

import java.io.*;
import java.util.*;

/*
 * 常用图片的格式可以通过读取文件头部分获得：
 * 常用图片的格式可以通过读取文件头部分获得(16进制)
 */
public class Picture {

	public static void main(String[] args) {

		InputStream fis = null;
		Scanner input = new Scanner(System.in);
		System.out.println("请输入文件名：");
		String path = input.next();
		File file = new File(path);
		int blen = 0;
		String[] str = { ".jpg", ".png", ".gif", ".bmp" };

		String[] arr = { "FFD8", "89504E470D0A1A0A", "474946383961", "424D" };
		String run = null;
		for (int i = 0; i < str.length; i++) {
			if (file.getName().endsWith(str[i])) {
				switch (i) {
				case 0:
					run = arr[0];
					blen = 2;
					break;
				case 1:
					run = arr[1];
					blen = 8;
					break;
				case 2:
					run = arr[2];
					blen = 6;
					break;
				case 3:
					run = arr[3];
					blen = 2;
					break;
				default:
					break;
				}
			}
		}

		if (blen == 0) {
			System.out.println("文件名不存在！");
			System.exit(0);
		}
		StringBuffer sb = new StringBuffer();
		System.out.println(sb);
		try {
			fis = new FileInputStream(file);
			byte[] b = new byte[blen];
			fis.read(b);
			for (int i = 0; i < b.length; i++) {
				String toHex = Integer.toHexString(b[i] & 0xFF).toUpperCase();
				if (toHex.length() < 2) {
					sb.append(0);
				}
				sb.append(toHex);
			}
			if (run.equals(sb.toString())) {
				System.out.println("文件名正确！");
			} else {
				System.out.println("文件名不匹配");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fis != null) {
					fis.close();
					input.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
